<template>
  <div
    v-if="alertMessage"
    :class="['alert', alertType, 'alert-dismissible', 'fade', 'show', 'alert-left']"
    role="alert"
    style="
      position: fixed;
      top: 20px;
      left: 50%;
      transform: translateX(-50%);
      z-index: 1050;
      width: 100%;
      max-width: 600px;
    "
  >
    <span class="alert-inner--icon" sytle="margin-left: 0px">
      <i :class="alertIcon"></i>
    </span>
    <span class="alert-inner--text">
      <strong>{{ alertTitle }}</strong> {{ alertMessage }}
    </span>
    <button type="button" class="close" @click="clearAlert">
      <span aria-hidden="true">&times;</span>
    </button>
  </div>
  <button
    v-if="userRole === 'teacher'"
    class="btn btn-sm btn-success upload-btn upload-btn-lg my-1"
    style="position: absolute; left: 80%"
    @click.stop="openUpload(index)"
  >
    上传
  </button>

  <!-- 上传资料弹窗 -->
<div v-if="showUploadModal" class="modal-backdrop">
  <div class="modal-content-box upload-modal-animate">
    <h5 class="mb-4 fw-bold text-center" style="letter-spacing:1px;">上传资料</h5>

    <div class="mb-3">
      <label class="form-label fw-semibold mb-1">选择文件</label>
      <input type="file" class="form-control" @change="handleFileChange" />
    </div>
    <div class="mb-3">
      <label class="form-label fw-semibold mb-1">资料链接/说明</label>
      <input v-model="uploadForm.link" class="form-control" placeholder="如需附带网盘链接或简要说明" />
    </div>
    <div class="mb-3">
      <label for="chapterSelect" class="form-label fw-semibold mb-1">选择章节</label>
      <select id="chapterSelect" v-model="selectedChapterId" class="form-select">
        <option disabled value="">请选择章节</option>
        <option v-for="chapter in chapters" :key="chapter.chapterId" :value="chapter.chapterId">
          {{ chapter.chapterName }}
        </option>
      </select>
    </div>
    <div class="mb-3">
      <label class="form-label fw-semibold mb-1">资料标签 <span class="text-muted small">(可选)</span></label>
      <input v-model="uploadForm.label" class="form-control" placeholder="标签（如讲义/课件/作业等）" />
    </div>
    <div class="d-flex justify-content-end gap-2 mt-2">
      <button class="btn btn-outline-secondary btn-sm rounded-pill px-3" @click="closeUpload">取消</button>
      <button class="btn btn-success btn-sm rounded-pill px-3" @click="confirmUpload">上传</button>
    </div>
  </div>
</div>

  <router-view />
</template>

<script setup>
  const chapters = ref([])
  const showUploadModal = ref(false)
  const uploadTargetIndex = ref(null)
  const selectedChapterId = ref('') // 绑定下拉选中的章节 ID
  const selectedFile = ref(null)
  const uploadForm = ref({
    name: '',
    type: '',
    link: '',
    label: '', // ✅ 新增
  })
  import { onMounted } from 'vue'
  import { ref } from 'vue'
  import axios from 'axios'
  import emitter from '@/eventBus'
  import { useRoute } from 'vue-router'
  import { useUserStore } from '@/stores/userStore'
  const userStore = useUserStore()
  const userId = userStore.user?.userId || ''

  const route = useRoute()
  const courseId = route.params.id
  const userRole = ref('') // 保存后端返回的角色
  async function fetchUserRole() {
    try {
      const res = await axios.get('/api/exercises/role', {
        params: {
          courseId,
          userId,
        },
      })
      userRole.value = res.data
      console.log('身份识别结果:', userRole.value)
    } catch (err) {
      console.error('获取用户身份失败', err)
      userRole.value = 'undefined'
    }
  }

  onMounted(async () => {
    const res = await axios.get(`/api/courses/${courseId}/chapters`)
    chapters.value = res.data
    if (chapters.value.length > 0) {
      selectedChapterId.value = chapters.value[0].chapterId // 默认选择第一个章节
    }

    await fetchUserRole() // ✅ 获取用户身份
  })

  async function confirmUpload() {
    const form = uploadForm.value
    const chapterId = selectedChapterId.value

    if (!chapterId) {
      alert('请选择章节')
      return
    }

    if (!form.name || !form.type || !selectedFile.value) {
      alert('请选择文件并填写资料名称与类型')
      return
    }

    const formData = new FormData()
    formData.append('file', selectedFile.value)
    formData.append('materialName', form.name)
    formData.append('courseId', courseId)
    formData.append('chapterId', chapterId)
    formData.append('materialLabel', form.label || '') // 允许为空

    try {
      for (const [key, value] of formData.entries()) {
        console.log(`${key}:`, value)
      }
      const response = await axios.post('/api/materials/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
        onUploadProgress: (progressEvent) => {
          const percent = Math.round((progressEvent.loaded * 100) / progressEvent.total)
          console.log(`上传进度: ${percent}%`)
        },
      })

      // 添加返回的资料到章节中（这里只是模拟）
      // 上传成功后将资料添加到对应章节 materials 中
      //   chapters.value[uploadTargetIndex.value].materials.push({
      //     id: response.data.materialId,
      //     name: response.data.materialName,
      //     label: response.data.materialLabel,
      //     uploadTime: response.data.uploadTime,
      //     link: `/api/materials/${response.data.materialId}/download`, // 或 response.data.materialPath
      //   })

      await fetchChapterMaterials(chapterId)
      // ✅ 触发上传成功事件
      emitter.emit('material-uploaded', { chapterId: selectedChapterId.value })

      console.log(JSON.stringify(chapters.value, null, 2))

      closeUpload()
      showAlert('alert-success', '上传成功！', 'fas fa-check', '资料上传成功')
    } catch (err) {
      // 上传失败
      showAlert('alert-danger', '上传失败！', 'fas fa-times', err?.response?.data || err.message)
    }
  }

  function openUpload(index) {
    uploadTargetIndex.value = index
    showUploadModal.value = true
    uploadForm.value = { name: '', type: '', link: '' }
  }

  function closeUpload() {
    showUploadModal.value = false
  }

  async function fetchChapterMaterials(chapterId) {
    try {
      const res = await axios.get(`/api/materials/${courseId}/chapter/${chapterId}`)
      const index = chapters.value.findIndex((c) => c.chapterId === chapterId)
      if (index !== -1) {
        const updated = {
          ...chapters.value[index],
          materials: res.data,
        }
        chapters.value.splice(index, 1, updated) // ✅ 替换整个对象，确保响应式
      }
    } catch (err) {
      console.error('刷新资料失败', err)
    }
  }

  function handleFileChange(e) {
    const file = e.target.files[0]
    if (!file) return

    selectedFile.value = file

    // 自动填入文件名
    uploadForm.value.name = file.name

    // 自动判断类型
    const ext = file.name.split('.').pop().toLowerCase()
    if (['pdf', 'ppt', 'pptx'].includes(ext)) uploadForm.value.type = 'ppt'
    else if (['doc', 'docx'].includes(ext)) uploadForm.value.type = 'doc'
    else if (['xls', 'xlsx'].includes(ext)) uploadForm.value.type = 'excel'
    else if (['pdf'].includes(ext)) uploadForm.value.type = 'pdf'
    else uploadForm.value.type = 'link'

    // 可选：预设一个链接为“本地上传”标识
    uploadForm.value.link = `已选择文件：${file.name}`
  }

  // 提示框内容和类型
  const alertMessage = ref('')
  const alertType = ref('alert-success') // Bootstrap class：'alert-danger'等
  const alertTitle = ref('Success!')
  const alertIcon = ref('fas fa-check') // 默认图标 ✅

  function showAlert(type, title, icon, message) {
    alertType.value = type
    alertTitle.value = title
    alertIcon.value = icon
    alertMessage.value = message

    setTimeout(() => {
      alertMessage.value = ''
    }, 3000) // 自动消失
  }

  function clearAlert() {
    alertMessage.value = ''
  }
</script>

<style scoped>
  .divider {
    border: none;
    height: 1px;
    background-color: #9d9d9d;
    margin: 8px 0 16px 0;
    border-radius: 4px;
  }

  .mb-4 {
    text-align: left;
    font-size: 35px;
  }

  .card-header {
    background-color: #104f91;
    color: white;
  }

  /* 弹窗样式 */
  .modal-backdrop {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.4);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 9999;
  }

  .modal-content-box {
    background-color: #fff;
    padding: 20px;
    border-radius: 8px;
    width: 400px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
  }

  /* 按钮间隔 */
  .gap-2 > * + * {
    margin-left: 0.5rem;
  }

  .card {
    border: 1px solid #dee2e6;
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    transition: transform 0.3s ease, box-shadow 0.3s ease;
    transform-origin: center center;
  }

  /* 鼠标悬停时放大 + 强化阴影 */
  .card:hover {
    transform: scale(1.05);
    box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15);
    z-index: 10;
  }

  .card-header {
    background-color: #326aa6;
    color: white;
    border-radius: 8px 8px 0 0;
    font-weight: 500;
    font-size: 18px;
  }

  .modal-content-box {
    border: 1px solid #ccc;
    border-radius: 10px;
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.2);
  }

  .mb-4 {
    margin-bottom: 1.5rem !important;
  }

  .btn-download {
    background-color: #28a745; /* 绿色 */
    color: #fff;
    border: none;
    border-radius: 10px;
    transition: transform 0.2s ease, box-shadow 0.2s ease;
  }

  .btn-download:hover {
    transform: scale(1.1);
    box-shadow: 0 4px 10px rgba(40, 167, 69, 0.3);
  }

  .btn-delete {
    background-color: #dc3545; /* 红色 */
    color: #fff;
    border: none;
    border-radius: 10px;
    transition: transform 0.2s ease, box-shadow 0.2s ease;
  }

  .btn-delete:hover {
    transform: scale(1.1);
    box-shadow: 0 4px 10px rgba(220, 53, 69, 0.3);
  }

  .material-name {
    font-size: 1.1rem;
    font-weight: 500;
    color: #333;
  }

  .upload-btn {
    transition: transform 0.2s ease, box-shadow 0.2s ease;
  }

  .upload-btn:hover {
    transform: scale(1.1);
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.15);
  }

  .upload-btn-lg {
    font-size: 1rem;
    font-weight: bold;
    background-color: #f8f9fa;
    border: 1px solid #ccc;
    padding: 8px 20px;
    border-radius: 8px;
    transition: transform 0.2s ease, box-shadow 0.2s ease;
  }

  .upload-btn-lg:hover {
    transform: scale(1.1);
    background-color: #e2e6ea;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  }

  .alert-left {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    gap: 10px;
  }

  .alert-left .alert-inner--icon {
    margin-right: 6px;
    font-size: 18px;
  }

  .alert-left .alert-inner--text {
    text-align: left;
    flex: 1;
  }

  .my-container {
    width: 70vw !important;
    margin: 0 auto;
  }

  .modal-backdrop {
  position: fixed;
  inset: 0;
  z-index: 2000;
  background: rgba(33,37,41,0.2);
  display: flex;
  align-items: center;
  justify-content: center;
}
.modal-content-box {
  background: #fff;
  border-radius: 1.5rem;
  box-shadow: 0 6px 40px 0 rgba(16, 79, 145, 0.09);
  padding: 2.2rem 2.5rem 1.6rem 2.5rem;
  min-width: 340px;
  max-width: 96vw;
  width: 400px;
  transition: box-shadow 0.2s;
  animation: modal-pop-in 0.27s cubic-bezier(.7,.3,.3,1);
}

@keyframes modal-pop-in {
  from { transform: translateY(20px) scale(0.97); opacity: 0; }
  to   { transform: translateY(0) scale(1); opacity: 1; }
}
.upload-modal-animate { /* 可自定义动画样式类名，增强弹窗动感 */ }

</style>
